import { stuCourseData, teaCourseData } from './mock';
const app = getApp();
Page({
  data: {
    nvabarData: {
      title: '课程日历',
      transmit: ''
    },
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    currentDate: '',
    weekDays: ['日', '一', '二', '三', '四', '五', '六'],
    calendarDays: [],
    selectedDate: '',
    currentCourses: [],
    userInfo_role: wx.getStorageSync('userInfo_role')//app.globalData.userInfo_role
  },
  onShow: function() {
    console.log('onShow')
    this.setData({
      userInfo_role: wx.getStorageSync('userInfo_role')
    })
     // 初始化当前日期
     const today = new Date();
     const currentDate = this.formatDate(today, 'picker');
     this.setData({
       currentDate: currentDate
     });
    this.getCourseData();
    this.generateCalendar();
    this.selectToday()
  },
  onLoad: function () {
  },
  // 获取课程信息
  getCourseData() {
    const { userInfo_role } = this.data
    let courseData = {}
    if (userInfo_role == 'student') {
      courseData = stuCourseData
    }
    if (userInfo_role == 'teacher') {
      courseData = teaCourseData
    }
    this.setData({
      courseData
    })
  },
  // 生成日历
  generateCalendar: function () {
    const { currentYear, currentMonth } = this.data;

    // 当月第一天
    const firstDay = new Date(currentYear, currentMonth - 1, 1);
    // 当月最后一天
    const lastDay = new Date(currentYear, currentMonth, 0);
    // 当月第一天是星期几
    const firstDayWeek = firstDay.getDay();
    // 当月总天数
    const daysInMonth = lastDay.getDate();

    let calendarDays = [];

    // 添加上个月末尾的几天
    const prevMonthLastDay = new Date(currentYear, currentMonth - 1, 0).getDate();
    for (let i = firstDayWeek - 1; i >= 0; i--) {
      const day = prevMonthLastDay - i;
      const date = new Date(currentYear, currentMonth - 2, day);
      const dateStr = this.formatDate(date);

      calendarDays.push({
        day: day,
        isCurrentMonth: false,
        isToday: false,
        hasCourse: this.hasCourse(dateStr),
        isSelected: false,
        date: dateStr
      });
    }

    // 添加当月的日期
    const today = new Date();
    const todayStr = this.formatDate(today);

    for (let i = 1; i <= daysInMonth; i++) {
      const date = new Date(currentYear, currentMonth - 1, i);
      const dateStr = this.formatDate(date);

      calendarDays.push({
        day: i,
        isCurrentMonth: true,
        isToday: dateStr === todayStr,
        hasCourse: this.hasCourse(dateStr),
        isSelected: false,
        date: dateStr
      });
    }

    // 添加下个月开始的几天，补齐6行
    const nextMonthDays = 42 - calendarDays.length;
    for (let i = 1; i <= nextMonthDays; i++) {
      const date = new Date(currentYear, currentMonth, i);
      const dateStr = this.formatDate(date);

      calendarDays.push({
        day: i,
        isCurrentMonth: false,
        isToday: false,
        hasCourse: this.hasCourse(dateStr),
        isSelected: false,
        date: dateStr
      });
    }

    // 将日期数组按周分组
    let groupedCalendarDays = [];
    for (let i = 0; i < calendarDays.length; i += 7) {
      groupedCalendarDays.push(calendarDays.slice(i, i + 7));
    }

    this.setData({
      calendarDays: groupedCalendarDays
    });
  },

  // 检查某天是否有课
  hasCourse: function (dateStr) {
    return this.data.courseData.hasOwnProperty(dateStr);
  },

  // 日期格式化
  formatDate: function (date, type = 'normal') {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();

    if (type === 'picker') {
      return `${year}-${month < 10 ? '0' + month : month}`;
    }

    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
  },

  // 月份改变
  onMonthChange: function (e) {
    const date = new Date(e.detail.value);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;

    this.setData({
      currentYear: year,
      currentMonth: month,
      currentDate: this.formatDate(date, 'picker')
    });

    this.generateCalendar();
  },

  // 上个月
  onPrevMonth: function () {
    let newYear = this.data.currentYear;
    let newMonth = this.data.currentMonth - 1;

    if (newMonth < 1) {
      newMonth = 12;
      newYear--;
    }

    const newDate = new Date(newYear, newMonth - 1, 1);

    this.setData({
      currentYear: newYear,
      currentMonth: newMonth,
      currentDate: this.formatDate(newDate, 'picker')
    });

    this.generateCalendar();
  },

  // 下个月
  onNextMonth: function () {
    let newYear = this.data.currentYear;
    let newMonth = this.data.currentMonth + 1;

    if (newMonth > 12) {
      newMonth = 1;
      newYear++;
    }

    const newDate = new Date(newYear, newMonth - 1, 1);

    this.setData({
      currentYear: newYear,
      currentMonth: newMonth,
      currentDate: this.formatDate(newDate, 'picker')
    });

    this.generateCalendar();
  },

  // 点击日期
  onDayTap: function (e) {
    const date = e.currentTarget.dataset.date;
    const courses = this.data.courseData[date] || [];

    // 更新选中状态
    const updatedCalendarDays = this.data.calendarDays.map(week => {
      return week.map(day => {
        return {
          ...day,
          isSelected: day.date === date
        };
      });
    });

    this.setData({
      selectedDate: date,
      currentCourses: courses,
      calendarDays: updatedCalendarDays
    });
  },

  // 选择今天
  selectToday: function () {
    const today = new Date();
    const todayStr = this.formatDate(today);
    const courses = this.data.courseData[todayStr] || [];

    // 更新选中状态
    const updatedCalendarDays = this.data.calendarDays.map(week => {
      return week.map(day => {
        return {
          ...day,
          isSelected: day.date === todayStr
        };
      });
    });

    this.setData({
      selectedDate: todayStr,
      currentCourses: courses,
      calendarDays: updatedCalendarDays
    });
  },
  goSign(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/checkIn/index?id=${id}`
    });
  },
});